package com.spzx.product.service.impl;

import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.Brand;
import com.spzx.product.mapper.BrandMapper;
import com.spzx.product.service.BrandService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.ServiceConfigurationError;

@Service
public class BrandServiceImpl implements BrandService {

    @Resource
    BrandMapper brandMapper;

    @Override
    public List<Brand> selectBrandlist(Brand brand) {
        return brandMapper.selectBrandlist(brand);
    }

    @Override
    public Brand selectBrandById(Long id) {

        return brandMapper.selectBrandById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBrand(Brand brand) {
        //新增品牌
        //检查品牌是否存在
        checkBrandNameUnique(brand);
        brand.setCreateBy(SecurityUtils.getUsername());
        return brandMapper.insertBrand(brand);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBrandById(Brand brand) {
        checkBrandNameUnique(brand);
        brand.setUpdateBy(SecurityUtils.getUsername());
        return brandMapper.updateBrandByid(brand);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeBrandByid(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
           throw  new ServiceException("缺少参数id");
        }
        return brandMapper.removeBrandByid(ids);
    }

    @Override
    public List<Brand> selectBrandListC3Id(Long c3Id) {
        return brandMapper.selectBrandListC3Id(c3Id);
    }

    @Override
    public List<Brand> selectBrandAll() {


        return brandMapper.selectBrandList2();
    }


    @Override
    public void checkBrandNameUnique(Brand brand) {
        //判断brand中是否有id  有则是更新 没有是新增    如果是新增 则id==-1  数据库中一定没有主键为-1的品牌
        Long id = brand.getId()==null?-1:brand.getId();
        //通过名字 查询 品牌是否存在
        Brand dbBrand =  brandMapper.selectBrandByName(brand.getName());
        //判断dbRand是否存在 存在则returnfalse
        // ServiceException 若依封装的异常类  抛出的是运行时异常
        //如果存在
        //新增时：查询到了同名品牌，-1和数据库中的记录id一定不同，可以进入代码块
        //更新时：查询到了同名品牌，数据库中的记录id 和更新提交的id 不同，表示重名了，可以进入代码块
        if (dbBrand !=null && !id.equals(dbBrand.getId()) ){
            throw  new ServiceException("品牌已存在");
        }


    }

}
